//
//  HJSendCodeController.m
//  KaiChat
//
//  Created by lx on 2023/10/17.
//

#import "HJSendCodeController.h"
#import "HJPasswordCodeView.h"
#import "HJTimer.h"
#import "QMUIButton.h"
#import "HJMinePresent.h"
#import "HJResetPasswordController.h"

@interface HJSendCodeController ()<HJPasswordCodeViewDelegate>

@property (nonatomic, assign) BOOL isReset;
@property (nonatomic, weak) UILabel *textLabel;
@property (nonatomic, weak) UILabel *subTextLabel;
@property (nonatomic, weak) HJPasswordCodeView *codeView;
@property (nonatomic, weak) QMUIButton *resendButton;
@property (nonatomic, strong) HJTimer *timer;
@property (nonatomic, assign) NSInteger lastTime;


@end

@implementation HJSendCodeController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    _lastTime = 0;
    
    UILabel *textLabel = [UILabel lableWithSuperView:self.view font:UIFontMediumMake(20) color:UIColor.tj_333333Color title:@"Verification" textAlignment:NSTextAlignmentLeft];
    [textLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(KNavBarHight + 12);
        make.left.offset(leftRightMargin);
    }];
    
    UILabel *subTextLabel = [UILabel lableWithSuperView:self.view font:UIFontMake(14) color:UIColor.tj_868391Color title:@"Please enter your verification code" textAlignment:NSTextAlignmentLeft];
    [subTextLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(textLabel.mas_bottom).offset(textSubTextLabelMargin);
        make.left.equalTo(textLabel);
    }];
    
    HJPasswordCodeView *codeView = [[HJPasswordCodeView alloc] initWithCount:6 margin:9].addTo(self.view);
    codeView.delegate = self;
    [codeView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.offset(0);
        make.top.equalTo(subTextLabel.mas_bottom).offset(60);
        make.width.offset(KScreenWidth - 40);
        make.height.offset(48);
    }];
    
    UILabel *tipLabel = [UILabel lableWithSuperView:self.view font:UIFontMake(12) color:UIColor.tj_868391Color title:@"Not received?" textAlignment:NSTextAlignmentLeft];
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(codeView.mas_bottom).offset(10);
        make.left.equalTo(codeView);
    }];
    
    QMUIButton *resendButton = [QMUIButton buttonWithSuperView:self.view font:UIFontMake(12) color:UIColor.tj_mainColor title:@"Resend"];
    [resendButton setTitleColor:UIColor.tj_BEBDCAColor forState:UIControlStateDisabled];
    [resendButton sizeToFit];
    [resendButton addTarget:self action:@selector(didClickResendButton:) forControlEvents:UIControlEventTouchUpInside];
    CGSize buttonSize = resendButton.tj_size;
    [resendButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(tipLabel.mas_right).offset(7);
        make.width.offset(buttonSize.width);
        make.height.offset(buttonSize.height);
        make.centerY.equalTo(tipLabel);
    }];
    
    _textLabel = textLabel;
    _subTextLabel = subTextLabel;
    _resendButton = resendButton;
    _timer = [HJTimer timer];
    [self startCountdown];
    _codeView = codeView;
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(500 * NSEC_PER_MSEC)), dispatch_get_main_queue(), ^{
        [self.codeView.textField becomeFirstResponder];
    });
}

- (void)startCountdown {
    TJWeakify(self);
    [_timer start:60 countdownOngoing:^(NSInteger time) {
        weakself.resendButton.enabled = NO;
        [weakself.resendButton setTitle:[NSString stringWithFormat:@"%lus Resend", time] forState:UIControlStateDisabled];
        [weakself.resendButton sizeToFit];
        CGSize buttonSize = weakself.resendButton.tj_size;
        [weakself.resendButton mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.offset(buttonSize.width);
        }];
    } countdownEnd:^{
        weakself.resendButton.enabled = YES;
        [weakself.resendButton setTitle:@"Resend" forState:UIControlStateNormal];
        [weakself.resendButton sizeToFit];
        CGSize buttonSize = self.resendButton.tj_size;
        [weakself.resendButton mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.offset(buttonSize.width);
        }];
    }];
}

- (void)didClickResendButton:(QMUIButton *)button {
    [HJHUD showLoadingInView:self.view];
    if (_sendCodeType == HJSendCodeTypeForgetPassword) {
        [HJMinePresent sendResetPasswordEmailCode:_email complete:^(NSError * _Nullable error) {
            if (!error) {
                self.isReset = YES;
                [self startCountdown];
            }
        }];
        return;
    }
    
    [HJMinePresent sendRegisterEmailCode:_email complete:^(NSError * _Nullable error) {
        if (!error) {
            self.isReset = YES;
            [self startCountdown];
        }
    }];
    
}

- (void)textDidChange:(HJPasswordCodeView *)passwordCodeView text:(NSString *)text {
    
    if (text.length == 6) {
        //判断2s之内只能请求一次
        NSTimeInterval currentTimeInterval = [NSDate date].timeIntervalSince1970;
        if (currentTimeInterval - _lastTime < 2) {
            return;
        }
        _lastTime = currentTimeInterval;
        
        [HJHUD showLoadingInView:self.view];
        
        if (_sendCodeType == HJSendCodeTypeForgetPassword) {
            [HJMinePresent verifyResetPasswordCodeWithEmail:_email code:text complete:^(NSError * _Nullable error) {
                if (!error) {
                    HJResetPasswordController *setPasswordController = [[HJResetPasswordController alloc] init];
                    setPasswordController.email = self.email;
                    [self.navigationController pushViewController:setPasswordController];
                }
            }];
            return;
        }
        [HJMinePresent verifyRegisterCodeWithEmail:_email code:text complete:^(NSError * _Nullable error) {
   
        }];
    }
}

- (void)setIsReset:(BOOL)isReset {
    _isReset = isReset;
    
    if (_isReset) {
        _textLabel.text = @"Verification code has been sent to";
        _subTextLabel.text = self.email;
        _textLabel.font = UIFontMake(14);
        _textLabel.textColor = UIColor.tj_868391Color;
        _subTextLabel.font = UIFontMediumMake(20);
        _subTextLabel.textColor = UIColor.tj_333333Color;
    } else {
        _textLabel.text = @"Verification";
        _subTextLabel.text = @"Please enter your verification code";
        _textLabel.font = UIFontMediumMake(20);
        _subTextLabel.font = UIFontMake(14);
        _textLabel.textColor = UIColor.tj_333333Color;
        _subTextLabel.textColor = UIColor.tj_868391Color;
    }
}
 
- (void)dealloc {
    NSLog(@"%s", __func__);
}

- (BOOL)hiddenBackgroundView {
    return NO;
}

@end
